import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
// import Login from '@/views/Login'
import Layout from '@/views/Layout'
// import Home from '@/views/Home'
// import User from '@/views/User'
// import Search from '@/views/Search'
// import SearchResult from '../views/Search/SearchResult'
// import ArticleDetails from '../views/ArticleDetails'
// import UserEdit from '../views/User/UserEdit'
// import Chat from '../views/Chat'
// Vue.use在vue上注册全局插件
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('../views/Login')
  },
  // 1.8. Login.vue 和 Layout.vue 是一级路由页面
  // Home.vue和User.vue应该是嵌入在Layout.vue页面里的二级路由页面
  {
    path: '/Layout',
    component: Layout,
    redirect: '/Layout/Home',
    children: [
      {
        path: 'Home',
        component: () => import('../views/Home'),
        // isRecord是否需要设置滚动位置
        meta: { isRecord: true, top: 0 }
      },
      {
        path: 'User',
        component: () => import('../views/User')
      }
    ]
  },
  {
    path: '/search',
    component: () => import('../views/Search')
  },
  {
    path: '/search/:keywords',
    component: () => import('../views/Search/SearchResult')
  },
  {
    path: '/articledetail',
    component: () => import('../views/ArticleDetails')
  },
  {
    path: '/user_edit',
    component: () => import('../views/User/UserEdit')
  },
  {
    path: '/chat',
    component: () => import('../views/Chat')
  }
]

const router = new VueRouter({
  routes
})
// 前置路由守卫：
// 如果路由在登录页就正常放行
// 否则在其他路由判断有没有token如果没有token直接跳到登录页
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    next()
  } else {
    if (store.state.token) {
      next()
    } else {
      next('/login')
    }
  }
})

// 路由后置守卫
// 路由进入home页面之后把之前记录的滚动条高度的位置重新赋值给该页面
// to表示准备要去的路由页面
// 如果isRecord为true需要把滚动条高度感到对应的页面
router.afterEach((to, from) => {
  if (to.meta.isRecord) {
    setTimeout(() => {
      window.scrollTo(0, to.meta.top)
    }, 0)
  }
})
export default router
